package com.alcatel_lucent.osp.config;

import org.logicalcobwebs.proxool.admin.servlet.AdminServlet;
import org.springframework.orm.hibernate3.support.OpenSessionInViewFilter;
import org.springframework.util.Assert;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.Filter;
import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;

/**
 * Created by guoshunw on 2014/10/8.
 */
public class OSPWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{AppConfig.class};
    }

    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(true);

        OpenSessionInViewFilter openSessionInViewFilter = new OpenSessionInViewFilter();

        return new Filter[]{characterEncodingFilter, openSessionInViewFilter};
    }

    @Override
    protected void registerContextLoaderListener(ServletContext servletContext) {
        super.registerContextLoaderListener(servletContext);
        // add other listener
        addCustomServlets(servletContext);
    }

    private void addCustomServlets(ServletContext servletContext){
        //add proxool admin filter
        AdminServlet proxoolAdminServlet = new AdminServlet();
        String servletName = "proxoolAdmin";
        ServletRegistration.Dynamic registration = servletContext.addServlet(servletName, proxoolAdminServlet);
        Assert.notNull(registration,
                "Failed to register servlet with name '" + servletName + "'." +
                        "Check if there is another servlet registered under the same name.");
        registration.addMapping("/padmin");
        // add struts filter
    }

    /**
     * for webmvc servlet config
     */
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{OSPWebConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}
